package com.vxdata.utils.modules.utils;

import com.alibaba.fastjson2.JSONObject;
import com.vxdata.common.core.domain.AjaxResult;
import com.vxdata.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 接口请求MD5加密
 */
@Service
public class Md5AndHttp {

    @Value("${synchroUrl}")
    private String synchroUrl;

    // MD5加密的用户名
    private static final String USERNAME = "case_8+x";
    // MD5加密的密码
    private static final String PASSWORD = "f38zu3zja!395^3fj";


    /**
     * 推送案件到视频专网
     *
     * @param caseId 案件id
     */
    public AjaxResult pushCaseToVideo(Long caseId) {
        // 要传递的信息
        List<Object> list = new ArrayList<>();

        // MD5加密
        long time = System.currentTimeMillis();
        StringBuilder rawData = new StringBuilder();
        rawData.append(caseId);
        rawData.append("$");
        rawData.append(time);
        rawData.append("$");
        rawData.append(USERNAME);
        rawData.append("$");
        rawData.append(PASSWORD);
        String sign = DigestUtils.md5DigestAsHex(rawData.toString().getBytes());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("caseId", caseId);
        jsonObject.put("time", time);
        jsonObject.put("sign", sign);
        jsonObject.put("case", list);

        JSONObject synchro = synchro(jsonObject);
        if (synchro != null) {
            return AjaxResult.success(synchro);
        }
        return AjaxResult.error();
    }


    /**
     * 政务网视频同步
     *
     * @param object 案件信息
     * @return 推送结果
     */
    public JSONObject synchro(JSONObject object) {
        String jsonStr = null;
        int time = 0;
        do {
            String url = synchroUrl;
            HashMap<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json;charset=UTF-8");
            header.put("accept", "application/json;charset=UTF-8");
            String respStr = HttpUtils.sendPost(url, object.toString(), header);
            if (StringUtils.isNotEmpty(respStr)) {
                jsonStr = respStr;
                break;
            }
            time++;
            if (time >= 3) {
                break;
            }
        } while (true);
        return JSONObject.parseObject(jsonStr);
    }
}
